<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>银行卡管理</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
  <div class="d-flex">
    <nav class="flex-column bg-dark text-white p-3" style="width: 220px; height: 100vh;">
      <h4>后台管理</h4>
      <ul class="nav flex-column">
        <li class="nav-item"><a href="/admin/customers" class="nav-link text-white">客户管理</a></li>
        <li class="nav-item"><a href="/admin/cards" class="nav-link text-white active">银行卡管理</a></li>
        <li class="nav-item"><a href="/admin/deposits" class="nav-link text-white">存款业务管理</a></li>
        <li class="nav-item"><a href="/admin/transactions" class="nav-link text-white">交易管理</a></li>
      </ul>
    </nav>
    <main class="flex-fill p-4">
      <h3>银行卡管理</h3>
      <button class="btn btn-success mb-2">新增银行卡</button>
      <button class="btn btn-info mb-2">导出CSV</button>
      <button class="btn btn-info mb-2" data-bs-toggle="modal" data-bs-target="#searchModal">查询</button>
      <div class="modal fade" id="searchModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <form id="searchForm">
              <div class="modal-header">
                <h5 class="modal-title">查询条件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <input type="text" class="form-control mb-2" id="searchCardID" placeholder="卡号">
                <input type="text" class="form-control mb-2" id="searchCustomerID" placeholder="客户编号">
                <select class="form-select mb-2" id="searchIsReportLoss">
                  <option value="">挂失状态</option>
                  <option value="否">否</option>
                  <option value="是">是</option>
                </select>
                <input type="number" class="form-control mb-2" id="searchMinBalance" placeholder="最小余额">
                <input type="number" class="form-control mb-2" id="searchMaxBalance" placeholder="最大余额">
                <input type="date" class="form-control mb-2" id="searchStartDate" placeholder="开户起始日期">
                <input type="date" class="form-control mb-2" id="searchEndDate" placeholder="开户结束日期">
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">确定</button>
              </div>
            </form>
          </div>
        </div>
      </div>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>卡号</th>
            <th>存款类型</th>
            <th>开户日期</th>
            <th>开户金额</th>
            <th>余额</th>
            <th>密码</th>
            <th>是否挂失</th>
            <th>客户编号</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="cards-tbody">
        </tbody>
      </table>
    </main>
  </div>
  <!-- 通用编辑/删除 Modal -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form id="editForm">
          <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">编辑</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" id="modalBody"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="submit" class="btn btn-primary" id="modalSaveBtn">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <script src="/static/js/main.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
  async function loadCards() {
    const res = await fetch('/api/admin/cards');
    const data = await res.json();
    const tbody = document.getElementById('cards-tbody');
    tbody.innerHTML = '';
    data.forEach(card => {
      tbody.innerHTML += `<tr>
        <td>${card.cardID}</td>
        <td>${card.savingID}</td>
        <td>${card.openDate ? card.openDate : ''}</td>
        <td>${card.openMoney}</td>
        <td>${card.balance}</td>
        <td>******</td>
        <td>${card.IsReportLoss}</td>
        <td>${card.customerID}</td>
        <td>
          <button class='btn btn-sm btn-primary' onclick='openEditModal(${JSON.stringify(card)})'>编辑</button>
          <button class='btn btn-sm btn-danger' onclick='openDeleteModal("${card.cardID}")'>删除</button>
        </td>
      </tr>`;
    });
  }
  document.addEventListener('DOMContentLoaded', loadCards);

  // 新增银行卡
  if(document.querySelector('.btn-success')){
    document.querySelector('.btn-success').onclick = function() {
      document.getElementById('modalTitle').innerText = '新增银行卡';
      document.getElementById('modalBody').innerHTML = `
        <div class="mb-3">
          <label class="form-label">卡号</label>
          <input type="text" class="form-control" id="editCardID">
        </div>
        <div class="mb-3">
          <label class="form-label">存款类型</label>
          <input type="text" class="form-control" id="editCurID">
        </div>
        <div class="mb-3">
          <label class="form-label">存款业务ID</label>
          <input type="number" class="form-control" id="editSavingID">
        </div>
        <div class="mb-3">
          <label class="form-label">开户日期</label>
          <input type="date" class="form-control" id="editOpenDate">
        </div>
        <div class="mb-3">
          <label class="form-label">开户金额</label>
          <input type="number" class="form-control" id="editOpenMoney">
        </div>
        <div class="mb-3">
          <label class="form-label">余额</label>
          <input type="number" class="form-control" id="editBalance">
        </div>
        <div class="mb-3">
          <label class="form-label">密码</label>
          <input type="password" class="form-control" id="editPass">
        </div>
        <div class="mb-3">
          <label class="form-label">是否挂失</label>
          <select class="form-select" id="editIsReportLoss">
            <option value="否">否</option>
            <option value="是">是</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">客户编号</label>
          <input type="number" class="form-control" id="editCustomerID">
        </div>
      `;
      document.getElementById('modalSaveBtn').onclick = saveNewCard;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    };
  }
  async function saveNewCard(e) {
    e.preventDefault();
    const cardID = document.getElementById('editCardID').value;
    const curID = document.getElementById('editCurID').value;
    const savingID = document.getElementById('editSavingID').value;
    const openDate = document.getElementById('editOpenDate').value;
    const openMoney = document.getElementById('editOpenMoney').value;
    const balance = document.getElementById('editBalance').value;
    const pass = document.getElementById('editPass').value;
    const IsReportLoss = document.getElementById('editIsReportLoss').value;
    const customerID = document.getElementById('editCustomerID').value;
    const res = await fetch('/api/admin/cards', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cardID, curID, savingID, openDate, openMoney, balance, pass, IsReportLoss, customerID })
    });
    if ((await res.json()).msg === '银行卡添加成功') {
      alert('新增成功');
      location.reload();
    } else {
      alert('新增失败');
    }
  }
  // 编辑银行卡
  function openEditModal(card) {
    document.getElementById('modalTitle').innerText = '编辑银行卡';
    document.getElementById('modalBody').innerHTML = `
      <input type="hidden" id="editCardID" value="${card.cardID}">
      <div class="mb-3">
        <label class="form-label">余额</label>
        <input type="number" class="form-control" id="editBalance" value="${card.balance}">
      </div>
      <div class="mb-3">
        <label class="form-label">是否挂失</label>
        <select class="form-select" id="editIsReportLoss">
          <option value="否" ${card.IsReportLoss === '否' ? 'selected' : ''}>否</option>
          <option value="是" ${card.IsReportLoss === '是' ? 'selected' : ''}>是</option>
        </select>
      </div>
    `;
    document.getElementById('modalSaveBtn').onclick = saveEditCard;
    new bootstrap.Modal(document.getElementById('editModal')).show();
  }
  async function saveEditCard(e) {
    e.preventDefault();
    const cardID = document.getElementById('editCardID').value;
    const balance = document.getElementById('editBalance').value;
    const IsReportLoss = document.getElementById('editIsReportLoss').value;
    const res = await fetch(`/api/admin/cards/${cardID}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ balance, IsReportLoss })
    });
    if ((await res.json()).msg === '银行卡信息已更新') {
      alert('保存成功');
      location.reload();
    } else {
      alert('保存失败');
    }
  }
  // 删除银行卡
  function openDeleteModal(cardID) {
    document.getElementById('modalTitle').innerText = '删除确认';
    document.getElementById('modalBody').innerHTML = `<p>确定要删除卡号 ${cardID} 吗？</p>`;
    document.getElementById('modalSaveBtn').onclick = function(e) {
      e.preventDefault();
      deleteCard(cardID);
    };
    new bootstrap.Modal(document.getElementById('editModal')).show();
  }
  async function deleteCard(cardID) {
    const res = await fetch(`/api/admin/cards/${cardID}`, { method: 'DELETE' });
    if ((await res.json()).msg === '银行卡已删除') {
      alert('删除成功');
      location.reload();
    } else {
      alert('删除失败');
    }
  }
  document.getElementById('searchForm').onsubmit = async function(e) {
    e.preventDefault();
    const params = new URLSearchParams({
      cardID: document.getElementById('searchCardID').value,
      customerID: document.getElementById('searchCustomerID').value,
      IsReportLoss: document.getElementById('searchIsReportLoss').value,
      min_balance: document.getElementById('searchMinBalance').value,
      max_balance: document.getElementById('searchMaxBalance').value,
      start_date: document.getElementById('searchStartDate').value,
      end_date: document.getElementById('searchEndDate').value
    });
    const res = await fetch('/api/admin/cards/search?' + params.toString());
    const data = await res.json();
    const tbody = document.getElementById('cards-tbody');
    tbody.innerHTML = '';
    data.forEach(card => {
      tbody.innerHTML += `<tr>
        <td>${card.cardID}</td>
        <td>${card.savingID}</td>
        <td>${card.openDate ? card.openDate : ''}</td>
        <td>${card.openMoney}</td>
        <td>${card.balance}</td>
        <td>******</td>
        <td>${card.IsReportLoss}</td>
        <td>${card.customerID}</td>
        <td>
          <button class='btn btn-sm btn-primary' onclick='openEditModal(${JSON.stringify(card)})'>编辑</button>
          <button class='btn btn-sm btn-danger' onclick='openDeleteModal("${card.cardID}")'>删除</button>
        </td>
      </tr>`;
    });
    bootstrap.Modal.getInstance(document.getElementById('searchModal')).hide();
  };
  </script>
</body>
</html>